from enum import IntEnum
from typing import Optional, List
from uuid import uuid4
from beanie import Document
from bson import ObjectId
from pydantic import Field, BaseModel
from datetime import datetime
class ContentType(IntEnum):
    TEXT = 1
    IMAGE = 3
    AUDIO = 2
    VIDEO = 3
    FILE = 4
    SYSTEM_NOTICE = 5
    LOCATION = 6
    RICH_TEXT = 7

class ChatMessage(BaseModel):
    """聊天消息文档模型"""
    # 消息元数据
    sender_id: str = Field(..., description="发送者id")
    receiver_id: str = Field(..., description="接受者id")
    is_group: bool = False
    content_type: ContentType = Field(ContentType.TEXT, description="消息类型")
    content: str = Field(..., description="接受者id")
    gridfs_file_id: Optional[str] = Field(None, description="图片二进制数据存放位置id")
    created_at: datetime = Field(default_factory=lambda: datetime.now())
    updated_at: datetime = Field(default_factory=lambda: datetime.now())



class ChatMessageModel(Document,ChatMessage):
    msg_id: str = Field(default_factory=lambda: str(uuid4()))
    seq_id: int = Field(..., description="会话内消息序列号")
    session_id: str = Field(..., description="会话id")
    type: str = Field(..., description="消息类型")
    class Settings:
        name = "chat_messages"

    # 自定义序列化方法
    def dict(self, **kwargs):
        data = super().dict(**kwargs)
        # 将 ObjectId 转换为字符串
        if '_id' in data and isinstance(data['_id'], ObjectId):
            data['_id'] = str(data['_id'])
        return data

    @staticmethod
    def generate_session_id(send_id: str, receiver_id: str, is_group: bool = False) -> str:
        """生成会话ID"""
        if is_group:
            return f"group_{receiver_id}"
        else:
            # 排序ID确保唯一会话
            ids = sorted([send_id, receiver_id])
            return f"p2p_{ids[0]}_{ids[1]}"


class UpdateConversationRequest(BaseModel):
    questions: List[ str]
    answers: List[ str]
    template_name:str
class DeleteConversationRequest(BaseModel):
    device_id: str
    wx_id: str

class MqMessage(BaseModel):
    """MQ消息模型"""
    from_user: str
    to_user: str
    content: str
    msg_id: int
    msg_type: int
    create_time: int
    current_user: str
    key: str

class WebHookMessage(BaseModel):
    """WebHook消息模型"""
    from_user: str
    from_nick:str
    to_user: str
    content: str
    msg_id: int
    msg_type: int
    create_time: int
    current_user: Optional[str]
    is_self: bool
    group: bool
    sender_in_group: Optional[str]
    key: Optional[str]

class AndroidAppMQMessage(BaseModel):
    """Android App MQ消息模型"""
    phone: str
    device_id: str
    description: Optional[str]
    name: Optional[str]
    customer_id: str
    task_id: int
    time: datetime = Field(default_factory=lambda: datetime.now())